import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/modules/auth/store'

// 路由配置
const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/modules/auth/login.vue'),
    meta: {
      title: '登录',
      requiresAuth: false
    }
  },
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/components/layout/Layout.vue'),
    redirect: '/dashboard',
    meta: {
      requiresAuth: true
    },
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/modules/dashboard/index.vue'),
        meta: {
          title: '仪表板',
          icon: 'Dashboard'
        }
      },
      {
        path: '/users',
        name: 'Users',
        component: () => import('@/modules/user/list.vue'),
        meta: {
          title: '用户管理',
          icon: 'User'
        }
      },
      {
        path: '/roles',
        name: 'Roles',
        component: () => import('@/modules/role/list.vue'),
        meta: {
          title: '角色管理',
          icon: 'UserFilled'
        }
      },
      {
        path: '/permissions',
        name: 'Permissions',
        component: () => import('@/modules/permission/list.vue'),
        meta: {
          title: '权限管理',
          icon: 'Lock'
        }
      },
      {
        path: '/upload',
        name: 'Upload',
        component: () => import('@/modules/upload/list.vue'),
        meta: {
          title: '文件管理',
          icon: 'Upload'
        }
      },
      {
        path: '/profile',
        name: 'Profile',
        component: () => import('@/modules/auth/profile.vue'),
        meta: {
          title: '个人中心',
          icon: 'User'
        }
      }
    ]
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('@/views/404.vue'),
    meta: {
      title: '页面不存在'
    }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()

  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - X-Admin`
  }

  // 检查是否需要认证
  if (to.meta.requiresAuth !== false) {
    if (!userStore.token) {
      next('/login')
      return
    }

    // 如果有token但没有用户信息，获取用户信息
    if (!userStore.userInfo) {
      try {
        await userStore.getUserInfo()
      } catch (error) {
        // 获取用户信息失败，可能是token过期，使用本地登出
        userStore.localLogout()
        next('/login')
        return
      }
    }
  }

  // 如果已登录访问登录页，重定向到首页
  if (to.path === '/login' && userStore.token) {
    next('/')
    return
  }

  next()
})

export default router
